package com.imooc.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.imooc.config.UpYunConfig;
import com.imooc.dataobject.ProductInfo;
import com.imooc.dto.CartDTO;
import com.imooc.enums.ProductStatusEnum;
import com.imooc.enums.ResultEnum;
import com.imooc.exception.SellException;
import com.imooc.repository.ProductInfoRepository;
import com.imooc.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * Created by 廖师兄
 * 2017-05-09 17:31
 *
 * @author alan
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Resource
    private ProductInfoRepository repository;
    @Resource
    private UpYunConfig upYunConfig;

    /**
     * Option的出现主要解决的目的就是减少空指针的出现
     */
    @Override
    public ProductInfo findOne(String productId) {

        // 使用Optional说明泛型里边的对象是一个可选值,这个值可能存在也可能不存在
        Optional<ProductInfo> productInfoOptional = repository.findById(productId);

        // 如果Optional中包裹的对象存在的话,则执行里边的lambda表达式
        productInfoOptional.ifPresent(e -> e.addImageHost(upYunConfig.getImageHost()));

        // 如果Optional中包裹的值不为空的时候,返回optional中的值,否则返回orElse参数列表中的值
        return productInfoOptional.orElse(null);

        // orElse 和 orElseGet 的区别在于 如果Optional中包裹的对象有值得时候,orElse还是会执行参数列表中的方法,而orElseGet则不会
        // return productInfoOptional.orElseGet(null);

    }

    @Override
    public List<ProductInfo> findUpAll() {

        return repository.findByProductStatus(ProductStatusEnum.UP.getCode()).stream()
                .map(e -> e.addImageHost(upYunConfig.getImageHost()))
                .collect(Collectors.toList());

    }

    @Override
    public Page<ProductInfo> findAll(Pageable pageable) {

        Page<ProductInfo> productInfoPage = repository.findAll(pageable);
        productInfoPage.getContent().stream()
                .forEach(e -> e.addImageHost(upYunConfig.getImageHost()));
        return productInfoPage;

    }

    @Override
    public ProductInfo save(ProductInfo productInfo) {
        return repository.save(productInfo).addImageHost(upYunConfig.getImageHost());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void increaseStock(List<CartDTO> cartDTOList) {

        for (CartDTO cartDTO : cartDTOList) {
            ProductInfo productInfo = repository.findById(cartDTO.getProductId()).orElse(null);
            if (productInfo == null) {
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            Integer result = productInfo.getProductStock() + cartDTO.getProductQuantity();
            productInfo.setProductStock(result);

            repository.save(productInfo);
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void decreaseStock(List<CartDTO> cartDTOList) {

        for (CartDTO cartDTO : cartDTOList) {
            ProductInfo productInfo = repository.findById(cartDTO.getProductId()).orElse(null);
            if (ObjectUtil.isNull(productInfo)) {
                // 商品不存在异常
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }

            Integer result = productInfo.getProductStock() - cartDTO.getProductQuantity();
            if (result < 0) {
                // 商品库存不足异常
                throw new SellException(ResultEnum.PRODUCT_STOCK_ERROR);
            }

            productInfo.setProductStock(result);

            repository.save(productInfo);
        }

    }

    @Override
    public ProductInfo onSale(String productId) {

        ProductInfo productInfo = repository.findById(productId).orElse(null);
        if (ObjectUtil.isNull(productInfo)) {
            throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
        }
        if (productInfo.getProductStatusEnum().equals(ProductStatusEnum.UP)) {
            throw new SellException(ResultEnum.PRODUCT_STATUS_ERROR);
        }

        // 更新
        productInfo.setProductStatus(ProductStatusEnum.UP.getCode());
        return repository.save(productInfo);

    }

    @Override
    public ProductInfo offSale(String productId) {

        ProductInfo productInfo = repository.findById(productId).orElse(null);
        if (ObjectUtil.isNull(productInfo)) {
            throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
        }
        if (productInfo.getProductStatusEnum().equals(ProductStatusEnum.DOWN)) {
            throw new SellException(ResultEnum.PRODUCT_STATUS_ERROR);
        }

        // 更新
        productInfo.setProductStatus(ProductStatusEnum.DOWN.getCode());
        return repository.save(productInfo);

    }

}
